from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
import jwt
from jwt import exceptions
from django.conf import settings
from rest_framework.response import Response


class JwtQueryParmasAuthentication(BaseAuthentication):
    def authenticate(self, request):
        salt = settings.SECRET_KEY
        payload, msg = None, None
        token = request.query_params.get('token')
        try:
            payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])
        except exceptions.ExpiredSignatureError:
            raise AuthenticationFailed({'code': 1003, 'error': "token 失效"})
        except jwt.DecodeError:
            raise AuthenticationFailed({'code': 1003, 'error': "token 认证失败"})
        except jwt.InvalidTokenError:
            raise AuthenticationFailed({'code': 1003, 'error': "非法的token"})
        return (payload, token)

        # 三种操作
        # 1. 抛出一次，后续程序不在执行
        # 2. return 一个元祖 （1,2）【认证通过以后】，认证通过，在视图中如果调用
        #    request.user 就是元祖的第一个值， request.auth就是元祖的第二个值
        # 3. None 下一次认证
